package cn.iocoder.yudao.module.shop.service.handlestrategy;

import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.shop.dal.dataobject.handlestrategyuser.ShopHandleStrategyUserDO;
import cn.iocoder.yudao.module.shop.service.handlestrategyuser.ShopHandleStrategyUserService;
import com.alipay.api.domain.Kv;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.shop.controller.admin.handlestrategy.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.handlestrategy.ShopHandleStrategyDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.shop.convert.handlestrategy.ShopHandleStrategyConvert;
import cn.iocoder.yudao.module.shop.dal.mysql.handlestrategy.ShopHandleStrategyMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 手工费结算策略 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopHandleStrategyServiceImpl implements ShopHandleStrategyService {

    @Resource
    private ShopHandleStrategyMapper handleStrategyMapper;

    @Resource
    private ShopHandleStrategyUserService handleStrategyUserService;

    @Override
    public Long createHandleStrategy(ShopHandleStrategyCreateReqVO createReqVO) {
        // 插入
//        List<ShopHandleStrategyDO> enabledList = handleStrategyMapper.selectEnabledList(createReqVO.getTenantId());
//        for(int i = 0; i<enabledList.size(); i++){
//            enabledList.get(i).setEnabled(false);
//        }
//
//        if(enabledList.size() > 0){
//            handleStrategyMapper.updateBatch(enabledList);
//        }

        ShopHandleStrategyDO handleStrategy = ShopHandleStrategyConvert.INSTANCE.convert(createReqVO);
        handleStrategyMapper.insert(handleStrategy);
        // 返回
        return handleStrategy.getId();
    }

    @Override
    public void updateHandleStrategy(ShopHandleStrategyUpdateReqVO updateReqVO) {
        // 校验存在
        validateHandleStrategyExists(updateReqVO.getId());

//        List<ShopHandleStrategyDO> enabledList = handleStrategyMapper.selectEnabledList(updateReqVO.getTenantId());
//        for(int i = 0; i<enabledList.size(); i++){
//            enabledList.get(i).setEnabled(false);
//        }
//
//        if(enabledList.size() > 0){
//            handleStrategyMapper.updateBatch(enabledList);
//        }

        // 更新
//        updateReqVO.setEnabled(true);
        ShopHandleStrategyDO updateObj = ShopHandleStrategyConvert.INSTANCE.convert(updateReqVO);
        handleStrategyMapper.updateById(updateObj);
    }

    @Override
    public void deleteHandleStrategy(Long id) {
        // 校验存在
        validateHandleStrategyExists(id);
        // 删除
        handleStrategyMapper.deleteById(id);
    }

    private void validateHandleStrategyExists(Long id) {
        if (handleStrategyMapper.selectById(id) == null) {
            throw exception(HANDLE_STRATEGY_NOT_EXISTS);
        }
    }

    @Override
    public ShopHandleStrategyDO getHandleStrategy(Long id) {
        return handleStrategyMapper.selectById(id);
    }

    @Override
    public List<ShopHandleStrategyDO> getHandleStrategyList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return handleStrategyMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ShopHandleStrategyDO> getHandleStrategyPage(ShopHandleStrategyPageReqVO pageReqVO) {
        return handleStrategyMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopHandleStrategyDO> getHandleStrategyList(ShopHandleStrategyExportReqVO exportReqVO) {
        return handleStrategyMapper.selectList(exportReqVO);
    }

    //阶梯结算
    private Integer strategyLadder(Integer count, String strategyStr){
        if (count == 0) {
            return 0;
        }

        String[] arr = strategyStr.split(";");
        if(arr.length == 0){
            return 0;
        }

        for(int i = 0; i<arr.length; i++){
            String item = arr[i];
            String[] kvArr = item.split(":");
            if(kvArr.length != 2){
                return 0;
            }

            if(count.equals(Integer.valueOf(kvArr[0]))){
                return count * Integer.valueOf(kvArr[1]);
            }

            //如果都没有匹配，选择最后一个
            if(i == arr.length -1){
                return count * Integer.valueOf(kvArr[1]);
            }
        }

        return 0;
    }


    // 获取当前可用的工资策略
    @Override
    public ShopHandleStrategyDO getValidStrategy(Long tenantId){
        List<ShopHandleStrategyDO> list = handleStrategyMapper.selectList(ShopHandleStrategyDO::getTenantId, tenantId);
        if(list.size() == 0){
            return null;
        }

        ShopHandleStrategyDO strategyDO = null;

        if(list.size() == 1){
            strategyDO = list.get(0);
        }else{
            for(int i = 0; i<list.size(); i++){
                if(list.get(i).getEnabled()){
                    strategyDO = list.get(i);
                    break;
                }
            }
        }

        return strategyDO;
    }

    @Override
    public Integer calcHandlePrice(Long userId, Integer count, Long tenantId){

        ShopHandleStrategyUserDO handleStrategyUserDO = handleStrategyUserService.getHandleStrategeByUserId(userId);
        if(handleStrategyUserDO == null){
            throw exception(HANDLE_STRATEGY_USER_NOT_BINDED);
        }

        ShopHandleStrategyDO strategyDO = getHandleStrategy(handleStrategyUserDO.getStrategyId());

        if(strategyDO == null){
            return 0;
        }

        return strategyLadder(count, strategyDO.getStrategy());
    }

    @Override
    public Integer calcFirstChargeBonus(Integer payPrice, Long tenantId){
        ShopHandleStrategyDO strategyDO = getValidStrategy(tenantId);

        if(strategyDO == null){
            return 0;
        }

        return payPrice * strategyDO.getFirstChargeBonusRate() / 100;
    }

}
